package com.parsechina.hpush.broker.parser;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.*;

/**
 * @author linfeng
 * @since 2016/11/22
 */
public class PublishMessage extends PushMessage {
    private static final long serialVersionUID = -6948859587620108392L;

    private MqttConnectReturnCode returnCode;
    private boolean sessionPresent;
    private boolean retained;
    private String topicName;
    private MqttQoS qos;
    private ByteBuf payload;
    private int messageId;
    private String clientId;
    private boolean local = true;

    public PublishMessage(MqttPublishMessage msg) {
        super(msg);
        this.topicName = msg.variableHeader().topicName();
        this.payload = msg.payload();
        this.messageId = msg.variableHeader().messageId();
        this.retained = msg.fixedHeader().isRetain();
        this.qos = msg.fixedHeader().qosLevel();
    }

    public PublishMessage() {
    }

    public ByteBuf getPayload() {
        return payload;
    }

    public String getTopicName() {
        return topicName;
    }

    public int getMessageId() {

        return messageId;
    }

    public boolean isEmptyPayload() {
        return !payload.isReadable();
    }

    public boolean isRetained() {
        return retained;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public boolean isLocal() {
        return local;
    }

    public void setLocal(boolean local) {
        this.local = local;
    }

    public MqttConnectReturnCode getReturnCode() {
        return returnCode;
    }

    public void setReturnCode(MqttConnectReturnCode returnCode) {
        this.returnCode = returnCode;
    }

    public boolean isSessionPresent() {
        return sessionPresent;
    }

    public void setSessionPresent(boolean sessionPresent) {
        this.sessionPresent = sessionPresent;
    }

    public void setRetained(boolean retained) {
        this.retained = retained;
    }

    public void setTopicName(String topicName) {
        this.topicName = topicName;
    }


    public MqttQoS getQos() {
        return qos;
    }

    public void setQos(MqttQoS qos) {
        this.qos = qos;
    }

    public void setPayload(ByteBuf payload) {
        this.payload = payload;
    }

    public void setMessageId(int messageId) {
        this.messageId = messageId;
    }

    public MqttPublishMessage build() {
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retained, 0);
        MqttPublishVariableHeader variableHeader = new MqttPublishVariableHeader(topicName, messageId);
        return new MqttPublishMessage(fixedHeader, variableHeader, payload);
    }

}
